<template>
  <div class="app-container">
    <el-container  v-loading="changeLoading"
                   element-loading-text="切换租户中..."
                   element-loading-spinner="el-icon-loading">
      <el-header class="filter-container">
        <!--        <el-input v-model="input_toolbar" placeholder="请输入用户名" style="width: 200px; " class="filter-item"></el-input>-->
                <el-select v-model="tempOrganize.tenant_id" placeholder="组织架构" class="filter-item" :clearable="true"
                           :disabled="isDisable" @change="changeTenant"
                           @clear="()=>{tempOrganize.tenant_id=''}">
                  <el-option
                    v-for="item in organizeList"
                    :key="item.id"
                    :label="item.label"
                    :value="item.id">
                  </el-option>
                </el-select>

                <el-button type="primary" icon="el-icon-search" @click="onSearch" style="width: 90px;" class="filter-item">搜索
                </el-button>
        <el-button type="primary" icon="el-icon-plus" @click="onCreate(0)" class="filter-item">创建年级</el-button>
      </el-header>
      <el-main>
        <el-table :data="temperList" style="width: 100%;" border
                  :header-cell-style="{background:'#e1e4e5',color:'#80878f'}">
          <el-table-column align="center" label="ID" width="120">
            <template slot-scope="scope">
              {{ scope.row.id }}
            </template>
          </el-table-column>
          <el-table-column align="center" label="年级" width="120">
            <template slot-scope="scope">
              {{ scope.row.name }}
            </template>
          </el-table-column>
          <el-table-column align="center" label="年级编码" width="120">
            <template slot-scope="scope">
              {{ scope.row.kcode }}
            </template>
          </el-table-column>
          <el-table-column align="center" label="班级数量" width="120">
            <template slot-scope="scope">
              {{ scope.row.classnum }}
            </template>
          </el-table-column>
          <el-table-column align="center" label="组织结构" width="120">
            <template slot-scope="scope">
              {{ scope.row.organize_code }}
            </template>
          </el-table-column>
          <el-table-column align="header-center" label="描述">
            <template slot-scope="scope">
              {{ scope.row.description }}
            </template>
          </el-table-column>
          <el-table-column align="center" label=操作>
            <template slot-scope="scope">
              <el-button type="primary" size="small" @click="handleEdit(scope)">编辑</el-button>
              <el-button type="danger" size="small" @click="handleDelete(scope)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <!--      创建用户面板-->
        <el-dialog
          :title="dialogTitle[dialogType]"
          :visible.sync="dialogVisible"
          :close-on-click-modal=false
          top="5vh">

          <el-form
            ref=""
            :model="temper"
            :rules="rules"
            label-width="100px"
            style=" width: 80%; margin-left:50px;">
            <el-form-item label="组织架构：" prop="account">
              <el-input
                placeholder="请输入内容"
                v-model="tempOrganize.tenant_name"
                :disabled="true">
              </el-input>
            </el-form-item>

            <el-form-item label="年级：" prop="">
              <el-select v-model="temper.kcode" @change="selectGrade" placeholder="请选择年级" style="width: 100%">
                <el-option v-for="(item,index) in GRADE_SYS"
                           :label="item.label"
                           :value="item.kcode"
                           :disabled="isDisabledSelectGrade(item)"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="创建班级：" prop="">
              <el-input-number v-model="temper.classnum" @change="handleChange_addClassNum" :min="0" :max="50"
                               label="描述文字" :disabled=" temper.kcode=='' "></el-input-number>
            </el-form-item>

            <el-form-item label="描述：" prop="describe">
              <!--              <el-input v-model.number="defaultOrder.describe"></el-input>-->
              <el-input
                type="textarea"
                :rows="2"
                placeholder="请输入内容"
                v-model="temper.description"
                maxlength="30"
                show-word-limit>
              </el-input>
            </el-form-item>


<!--            禁止在此项添加手动删除班级功能，请在【创建班级】项删除-->
            <el-form-item label="下辖班级：" >
                <el-row >
                  <el-col :span="4" v-for="item in classList">
                    <el-tag
                      type="info"
                      effect="plain"
                      size="medium "
                    >
                      {{ item.label }}
                    </el-tag>
                  </el-col>
                </el-row>



              <!--              <el-tree-->
              <!--                ref="tree"-->
              <!--                :check-strictly="true"-->
              <!--                :data="classList"-->
              <!--                show-checkbox-->
              <!--                node-key="path"-->
              <!--                class="permission-tree"-->
              <!--              />-->
              <!--              <template v-if="row.edit">-->
              <!--                <el-input v-model="row.title" class="edit-input" size="small" />-->
              <!--                <el-button-->
              <!--                  class="cancel-btn"-->
              <!--                  size="small"-->
              <!--                  icon="el-icon-refresh"-->
              <!--                  type="warning"-->
              <!--                  @click="cancelEdit(row)"-->
              <!--                >-->
              <!--                  cancel-->
              <!--                </el-button>-->
              <!--              </template>-->
              <!--              <span v-else>{{ row.title }}</span>-->
            </el-form-item>


            <el-form-item>
              <div style="text-align:right;">
                <el-button type="danger" @click="cancelConsumer">取消</el-button>
                <el-button type="primary" @click="confirmConsumer(dialogType)">确认</el-button>
              </div>
            </el-form-item>
          </el-form>

        </el-dialog>
      </el-main>

    </el-container>
  </div>
</template>

<script>
import { deepClone } from '@/utils'
import { getGrades, addGrade, updateGrade, deleteGrade } from '@/api/grade'
import { findObjByProp } from '@/utils/utilc'
import { getRooms } from '@/api/classmgt'
import { getConsumersCondition } from '@/api/basicmgt'

const defaultGrade = {
  id: '',
  kcode: '',//年级编码（唯一）
  name: '',//年级名称
  classnum: 0,//绑定班级数量
  organize_code: '',//组织架构code
  description: ''
}

const defaultClass = {
  id: '',
  kcode: '',//班级编码（唯一）规则：组织架构code+年级编码+C+序号
  label: '',//对外展示名称
  grade_code: '',//年级编码
  organize_code: '',//组织架构code
  room_code: '',//教室编码，对应摄像头
  description: ''
}

export default {
  name: 'grade',

  data() {
    return {
      rules: {
        // account:[{ required: true, message: '请选择套餐', trigger: 'blur' }],
        // passwd:[{ required: true, message: '请选择套餐', trigger: 'blur' }],
        // tel:[{ required: true, message: '请选择套餐', trigger: 'blur' }],
        // role:[{ required: true, message: '不能为空', trigger: 'blur' }],

      },
      input_toolbar: '',
      tempOrganize: {},
      dialogTitle: ['创建年级', '编辑年级'],
      temper: Object.assign({}, defaultGrade),
      temperList: [],
      GRADE_SYS: [],
      organizeList: {},
      dialogVisible: false,
      dialogType: '0',

      classList: [],

      roomList: [],
      changeLoading: false,



    }
  },

  computed: {

    isDisable: {
      get() {
        return this.user_role == 'RA0003' ? true : false
      },
      set(val) {
      }
    }
  },

  created() {
    // Mock: get all routes and roles list from server
    this.getGrades()
    this.getRooms()

  },

  methods: {

    onSearch() {
    },
    onCreate() {

      if (this.user_role == 'RA0003') {
        this.tempOrganize.tenant_id = this.user_organize
      }
      this.dialogVisible = true
      this.dialogType = 0
      this.$nextTick(() => {
        this.temper = Object.assign({}, defaultGrade)
        this.temper.organize_code = this.tempOrganize.tenant_id
        this.classList = []
      })
    },

    async getRooms() {

      if (this.tempOrganize.tenant_id != null && this.tempOrganize.tenant_id != '') {
        const res = await getRooms(this.tempOrganize.tenant_id)
        this.roomList = res.data.list
      }
      this.organizeList = await this.$global.ORGANIZELIST()
    },

    async getGrades() {

      if (this.tempOrganize.tenant_id != null && this.tempOrganize.tenant_id != '') {
        const res = await getGrades(this.tempOrganize.tenant_id)
        this.temperList = res.data
      }


      // this.tempOrganize = await this.$global.ORGANIZELIST()
      this.organizeList = await this.$global.ORGANIZELIST()



      this.GRADE_SYS = await this.$global.GRADE_SYS()

      this.temper.organize_code = this.tempOrganize.tenant_id

      // console.log('======' + JSON.stringify(this.GRADE_SYS))

    },

    async changeTenant(tenant) {

      console.log('切换租户：' + tenant)

      if (tenant != null && tenant != '') {

        // let tenantName = findObjByProp('tenantId', tenant, this.organizeList).tenantName

        this.changeLoading = true
        await this.$global.CHANGE_TENANT(tenant).then(
          (res) => {
            // console.log('changeTenant=true='+res)
            this.changeLoading = false

            this.$notify({
              title: 'Success',
              dangerouslyUseHTMLString: true,
              message: `租户切换成功 !`,
              type: 'success',
              duration:1500

            })
          },
          ()=>{
            this.tempOrganize.tenant_id=''
            this.changeLoading = false
            this.$notify({
              title: 'Error',
              dangerouslyUseHTMLString: true,
              message: `租户切换失败!`,
              type: 'error',
              duration:1500

            })
          }
        ).catch(error=>{
          this.tempOrganize.tenant_id=''
          this.changeLoading = false
          this.$notify({
            title: 'Error',
            dangerouslyUseHTMLString: true,
            message: `租户切换异常!`,
            type: 'error',
            duration:1500

          })
        })
      }
    },

    cancelConsumer() {
      this.dialogVisible = false
    },

    async confirmConsumer(type) {

      if (type == 0) {//创建

        const { data } = await addGrade(this.temper)
        this.temper.id = data.id
        // this.temper.kcode = data.kcode
        console.log('创建==' + JSON.stringify(this.temper))
        this.temperList.push(this.temper)
      } else {//edit
        await updateGrade(this.temper)
        for (let index = 0; index < this.temperList.length; index++) {
          if (this.temperList[index].id === this.temper.id) {
            this.temperList.splice(index, 1, Object.assign({}, this.temper))
            break
          }
        }
      }

      this.cancelConsumer()
    },

    handleAddConsumer() {
      this.temper = Object.assign({}, defaultGrade)
      if (this.$refs.tree) {
        this.$refs.tree.setCheckedNodes([])
      }
      this.dialogType = '0'
      this.dialogVisible = true
    },
    handleEdit(scope) {
      this.dialogType = '1'
      this.dialogVisible = true
      this.temper = deepClone(scope.row)
      this.$nextTick(() => {

      })
    },
    handleDelete({ $index, row }) {
      this.$confirm('确定要删除年级吗?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'})
        .then(async() => {
          await deleteGrade(row.id)
          this.temperList.splice($index, 1)
          this.$message({
            type: 'success',
            message: 'Delete succed !'
          })
        })
        .catch(err => {
          console.error(err)
        })
    },

    /***
     *
     * 创建班级
     * */
    handleChange_addClassNum(currentValue, oldValue) {
      console.log('handleChange_addClassNum==' + currentValue + '==' + this.temper.classnum)

      this.addClsss(currentValue - oldValue)
    },

    selectGrade(value) {
      for (let index in this.temper.classnum) {

      }

      this.temper.name = findObjByProp('kcode', value, this.GRADE_SYS).label

    },

    /**
     *
     * @param add
     */
    addClsss(value) {

      // if(Math.abs(value)>0){
        for (let i = 0; i < Math.abs(value); i++) {
          if(value>0){
            let classLength = this.classList.length
            let nextClassNo = classLength + 1
            let tempClass = Object.assign({}, defaultClass)
            tempClass.kcode = this.tempOrganize.tenant_id + this.temper.kcode + 'C' + nextClassNo
            tempClass.label = this.temper.name + nextClassNo + '班'
            tempClass.grade_code = this.temper.kcode
            tempClass.organize_code = this.tempOrganize.tenant_id
            this.classList.push(tempClass)
          }else{
            this.classList.pop()

          }
        }
      // }


      // if (add) {
      //   let classLength = this.classList.length
      //   let nextClassNo = classLength + 1
      //   let tempClass = Object.assign({}, defaultClass)
      //   tempClass.kcode = this.tempOrganize.tenant_id + this.temper.kcode + 'C' + nextClassNo
      //
      //   tempClass.label = this.temper.name + nextClassNo + '班'
      //   tempClass.grade_code = this.temper.kcode
      //   tempClass.organize_code = this.tempOrganize.tenant_id
      //
      //   this.classList.push(tempClass)
      // } else {
      //   this.classList.pop()
      // }

    },

    /**
     *
     * @param item 目标grade对象
     * @param index 目标对象所在下标
     * @returns {boolean}
     */
    isDisabledSelectGrade(temper) {

      if (this.temperList.length > 0) {
        let type = this.temperList.some(function(item) {

          return item.kcode == temper.kcode
        })
        return type
      } else {
        return false
      }

    },
    getDtId() {
      var d = new Date();
      var year = d.getFullYear();
      var month = d.getMonth() + 1;
      var date = d.getDate();
      var day = d.getDay();
      var hours = d.getHours();
      var minutes = d.getMinutes();
      var seconds = d.getSeconds();
      var ms = d.getMilliseconds();
      year = (year + "").substring(2);
      if (month <= 9)
        month = "0" + month;
      if (date <= 9)
        date = "0" + date;
      if (hours <= 9)
        hours = "0" + hours;
      if (minutes <= 9)
        minutes = "0" + minutes;
      if (seconds <= 9)
        seconds = "0" + seconds;
      let num = Math.ceil(Math.random()*100);
      var id = year + month + date + hours + minutes + seconds + num;
      return id;
    },



  }

}
</script>

<style scoped>

.underInputWords {
  font-size: small;
  color: #999 !important;
  padding: 0 5px !important
}


</style>
<style>
.el-table th {
  display: table-cell !important;
}
</style>
